

package org.catpay.modules.sys.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.catpay.common.annotation.SysLog;
import org.catpay.common.exception.RRException;
import org.catpay.common.utils.CommonMap;
import org.catpay.common.utils.Constant;
import org.catpay.modules.sys.entity.SysMenuEntity;
import org.catpay.modules.sys.service.ShiroService;
import org.catpay.modules.sys.service.SysMenuService;
import org.catpay.modules.sys.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.mapper.EntityWrapper;

/**
 * 系统菜单
 * 
 */
@RestController
@RequestMapping("/sys/menu")
public class SysMenuController extends AbstractController {
	
	@Autowired
	private SysMenuService sysMenuService;
	
	@Autowired
	private ShiroService shiroService;

	/**
	 * 导航菜单
	 */
	@PostMapping("/nav")
	public R<?> nav(){
		List<SysMenuEntity> menuList = sysMenuService.getUserMenuList(getUserId());
		Set<String> permissions = shiroService.getUserPermissions(getUserId());
		return R.ok(CommonMap.getMap().put("menuList", menuList).put("permissions", permissions));
	}
	
	/**
	 * 所有菜单列表
	 */
	@PostMapping("/list")
	@RequiresPermissions("sys:menu:list")
	public R<?> list(){
		List<SysMenuEntity> menuList = sysMenuService.selectList(new EntityWrapper<SysMenuEntity>().notIn("menu_id", 
				Constant.IGNORE_MENU).notIn("parent_id",Constant.IGNORE_MENU));
		for(int i=0; i<menuList.size();i++){
			for(int j=0; j<menuList.size();j++) {
				if(menuList.get(j).getMenuId() == menuList.get(i).getParentId()) {
					menuList.get(i).setParentName(menuList.get(j).getName());
				}
			}
		}

		return R.ok(menuList);
	}
	
	@PostMapping("/listAll")
	@RequiresPermissions("sys:menu:list")
	public R<?> listAll(){
		List<SysMenuEntity> menuList = sysMenuService.selectList(new EntityWrapper<SysMenuEntity>().orderBy("order_num"));
		for(int i=0; i<menuList.size();i++){
			for(int j=0; j<menuList.size();j++) {
				if(menuList.get(j).getMenuId() == menuList.get(i).getParentId()) {
					menuList.get(i).setParentName(menuList.get(j).getName());
				}
			}
		}

		return R.ok(menuList);
	}
	
	
	/**
	 * 选择菜单(添加、修改菜单)
	 */
	@PostMapping("/select")
	@RequiresPermissions("sys:menu:select")
	public R<?> select(){
		//查询列表数据
		List<SysMenuEntity> menuList = sysMenuService.queryNotButtonList();
		
		//添加顶级菜单
		SysMenuEntity root = new SysMenuEntity();
		root.setMenuId(0L);
		root.setName("一级菜单");
		root.setParentId(-1L);
		root.setOpen(true);
	//	menuList.add(root);
		
		List<Map<String,Object>> list = new ArrayList<>();
			list.add(getMenuList(root,menuList));
		
		return R.ok(CommonMap.getMap().put("menuList", list));
	}
	
	/**
	 * 菜单信息
	 */
	@GetMapping("/info/{menuId}")
	@RequiresPermissions("sys:menu:info")
	public R<?> info(@PathVariable("menuId") Long menuId){
		SysMenuEntity menu = sysMenuService.selectById(menuId);
		return R.ok(CommonMap.getMap().put("menu", menu));
	}
	
	/**
	 * 保存
	 */
	@SysLog("保存菜单")
	@PostMapping("/save")
	@RequiresPermissions("sys:menu:save")
	public R<?> save(@RequestBody @Validated SysMenuEntity menu){
		//数据校验
		verifyForm(menu);
		
		sysMenuService.insert(menu);
		
		return R.ok();
	}
	
	/**
	 * 修改
	 */
	@SysLog("修改菜单")
	@PostMapping("/update")
	@RequiresPermissions("sys:menu:update")
	public R<?> update(@RequestBody SysMenuEntity menu){
		//数据校验
		verifyForm(menu);
				
		sysMenuService.updateById(menu);
		
		return R.ok();
	}
	
	/**
	 * 删除
	 */
	@SysLog("删除菜单")
	@PostMapping("/delete/{menuId}")
	@RequiresPermissions("sys:menu:delete")
	public R<?> delete(@PathVariable("menuId") long menuId){
		if(menuId <= 4){
			return R.error("系统菜单，不能删除");
		}

		//判断是否有子菜单或按钮
		List<SysMenuEntity> menuList = sysMenuService.queryListParentId(menuId);
		if(menuList.size() > 0){
			return R.error("请先删除子菜单或按钮");
		}

		sysMenuService.delete(menuId);

		return R.ok();
	}
	
	/**
	 * 验证参数是否正确
	 */
	private void verifyForm(SysMenuEntity menu){
		if(StringUtils.isBlank(menu.getName())){
			throw new RRException("菜单名称不能为空");
		}
		
		if(menu.getParentId() == null){
			throw new RRException("上级菜单不能为空");
		}
		
		//菜单
		if(menu.getType() == Constant.MenuType.MENU.getValue()){
			if(StringUtils.isBlank(menu.getUrl())){
				throw new RRException("菜单URL不能为空");
			}
		}
		
		//上级菜单类型
		int parentType = Constant.MenuType.CATALOG.getValue();
		if(menu.getParentId() != 0){
			SysMenuEntity parentMenu = sysMenuService.selectById(menu.getParentId());
			parentType = parentMenu.getType();
		}
		//	else if(menu.getParentId() == 0 && (menu.getType() == Constant.MenuType.MENU.getValue()||menu.getType() == Constant.MenuType.BUTTON.getValue()))
//		{
//			throw new RRException("一级菜单只能新建目录");
//		}
//		
		if(menu.getType() == Constant.MenuType.CATALOG.getValue() &&  parentType == Constant.MenuType.CATALOG.getValue()) {
			throw new RRException("该菜单不能再添加目录");
		}
		
		//目录、菜单
		if(menu.getType() == Constant.MenuType.MENU.getValue()){
			if(parentType != Constant.MenuType.CATALOG.getValue()){
				throw new RRException("上级菜单只能为目录类型");
			}
			return ;
		}
		
		//按钮
		if(menu.getType() == Constant.MenuType.BUTTON.getValue()){
			if(parentType != Constant.MenuType.MENU.getValue()){
				throw new RRException("上级菜单只能为菜单类型");
			}
			return ;
		}
	}


	private Map<String,Object> getMenuList(SysMenuEntity $this,List<SysMenuEntity> menuList){
		Map<String,Object> result = CommonMap.getMap().put("id",$this.getMenuId())
				.put("name", $this.getName()).put("open", $this.getMenuId()==0).put("checked", $this.getMenuId()==0);
		List<Map<String,Object>> children = new ArrayList<>();
		for(SysMenuEntity menu: menuList) {
			if($this.getMenuId() == menu.getParentId()) {
				Map<String,Object> child = getMenuList(menu,menuList);
				children.add(child);
			}
		}
		if(!children.isEmpty())
			result.put("children", children);
		return result;
	}
}
